import { AppConsts } from '/@/abpPro/AppConsts';
import { abpService } from '/@/shared/abp';
import { localizationService } from '/@/shared/i18n';
import { Modal } from 'ant-design-vue';
import axios from 'axios';
import abpHttpConfiguration from './abp-http-configuration.service';

const apiHttpClient = axios.create({
  baseURL: AppConsts.remoteServiceBaseUrl,
  timeout: 300000,
});

// request interceptor
apiHttpClient.interceptors.request.use(
  (config: any) => {
    // token
    if (!!abpService.abp.auth.getToken()) {
      config.headers.common.Authorization = 'Bearer ' + abpService.abp.auth.getToken() || '';
    }
    // 多语言
    config.headers.common['.AspNetCore.Culture'] = abpService.abp.utils.getCookieValue(
      'Abp.Localization.CultureName',
    );
    config.headers.common['Accept-Language'] = abpService.abp.localization.currentLanguage.name;

    // 租户Id
    config.headers.common[abp.multiTenancy.tenantIdCookieName] =
      abpService.abp.multiTenancy.getTenantIdCookie() || '';
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  },
);

// response error interceptor
apiHttpClient.interceptors.response.use(
  (response) => {
    // 响应成功拦截器
    if (response.data.__abp) {
      response.data = response.data.result;
    }
    return response;
  },
  (error) => {
    return new Promise((resolve, reject) => {
      // 响应失败拦截器
      // 关闭所有模态框
      Modal.destroyAll();

      const errorResponse = error.response;
      const ajaxResponse = abpHttpConfiguration.getAbpAjaxResponseOrNull(error.response);
      if (ajaxResponse != null) {
        abpHttpConfiguration.handleAbpResponse(errorResponse, ajaxResponse);
        reject(error);
      }
    });
    // return Promise.reject(error);
  },
);

export default apiHttpClient;
